package desktop;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class Desktop extends JFrame{
    private int N_screen = 6; //计分屏（赛道）的个数
    private int N_match = 9; //赛局数
    private JLabel image = new JLabel(); //比赛图标
    private JTextField matchName_input = new JTextField(28); //比赛名称
    private List<Screen> screens = new ArrayList<>(); //计分屏
    private List<SetTeamName> setTeamNames = new ArrayList<>(); //设置赛道工具栏
    private List<ScoreTable> scoreTables = new ArrayList<>(); //主窗口各赛道信息
    private StorageManager storageManager = new StorageManager(scoreTables, screens, N_match, image, matchName_input, setTeamNames); //存储管理器
    static private Desktop desktop = null;

    static public Desktop getInstance(){
        if(desktop==null)
            desktop = new Desktop();
        return desktop;
    }

    Desktop(){
        initWindows();
        this.setLayout(new BorderLayout());
        this.add(initTop(), BorderLayout.NORTH);

        JPanel jPanel_left = new JPanel(); //左侧设置区
        jPanel_left.setLayout(new GridLayout(N_screen,1));
        for(SetTeamName setTeamName:setTeamNames)
            jPanel_left.add(setTeamName);
        this.add(jPanel_left,BorderLayout.WEST);

        JPanel jPanel_center = new JPanel(); //显示所有赛道的信息
        jPanel_center.setLayout(new GridLayout(N_screen,1));
        for(int j=0;j<N_screen;j++) {
            ScoreTable scoreTable = new ScoreTable(N_match);
            jPanel_center.add(scoreTable);
            scoreTables.add(scoreTable);
        }
        this.add(jPanel_center,BorderLayout.CENTER);

        this.add(new Monitor(),BorderLayout.EAST); //监控区
        final JFrame jFrame_this = this;
        this.setTitle("裁判系统");
        this.setExtendedState(JFrame.MAXIMIZED_BOTH);
        this.setSize(1400,800);
        this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        this.setVisible(true);
        this.setJMenuBar(initMenu());
        this.addWindowListener(new WindowListener() {
            @Override
            public void windowOpened(WindowEvent e) { }

            @Override
            public void windowClosing(WindowEvent e) {
                int flag = JOptionPane.showConfirmDialog(null, "您是否要保存本次比赛的数据？",
                        "退出系统", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
                if (JOptionPane.YES_OPTION == flag) {
                    storageManager.save();
                    System.exit(0);
                }
                else if(JOptionPane.NO_OPTION == flag)
                    System.exit(0);
                else
                    jFrame_this.setVisible(true);
            }

            @Override
            public void windowClosed(WindowEvent e) { }

            @Override
            public void windowIconified(WindowEvent e) { }

            @Override
            public void windowDeiconified(WindowEvent e) { }

            @Override
            public void windowActivated(WindowEvent e) { }

            @Override
            public void windowDeactivated(WindowEvent e) { }
        });
    }

    private void initWindows(){
        for(int i=1;i<=N_screen;i++){
            Screen screen = new Screen("计分屏"+i, N_match);
            SetTeamName setTeamName = new SetTeamName(i, screen);
            setTeamNames.add(setTeamName);
            screens.add(screen);
        }
    }

    private JPanel initTop(){
        JPanel jPanel = new JPanel();
        image.setIcon(new ImageIcon("src/main/resources/icon.jpg"));
        jPanel.add(image);

        JPanel jPanel1 = new JPanel();
        JLabel jLabel_setMatchName = new JLabel("设置比赛名称：");
        matchName_input.setText("第X届冰壶比赛");
        JButton jButton_matchName = new JButton("确定");
        jButton_matchName.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                for(int i=0;i<N_screen;i++)
                    screens.get(i).setMatchName(matchName_input.getText());
            }
        });
        for(int i=0;i<N_screen;i++)
            screens.get(i).setMatchName(matchName_input.getText());
        jPanel1.add(jLabel_setMatchName);
        jPanel1.add(matchName_input);
        jPanel1.add(jButton_matchName);
        JLabel jLabel_setPic = new JLabel("设置比赛赛标图");
        final JTextField Pic_input = new JTextField(28);
        JButton jButton_see = new JButton("浏览");
        jButton_see.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser jfc = new JFileChooser(); // 打开文件选择窗口
                jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
                jfc.setFileFilter(new FileFilter() {
                    @Override
                    public boolean accept(File f) {
                        if (f.isDirectory())
                            return true;
                        String extension = f.getName().substring(f.getName().lastIndexOf(".")+1);
                        return (extension.equals("gif") || extension.equals("jpeg") || extension.equals("jpg") || extension.equals("png") ||
                                extension.equals("GIF") || extension.equals("JPEG") || extension.equals("JPG") || extension.equals("PNG"));
                    }

                    @Override
                    public String getDescription() {
                        return "图片文件(*.jpg, *.jpeg, *.gif, *.png)";
                    }
                });
                jfc.showDialog(new JLabel(), "选择");
                if(jfc.getSelectedFile()!=null)
                    Pic_input.setText(jfc.getSelectedFile().getAbsolutePath());
            }
        });
        JButton jButton_picPath = new JButton("确定");
        jButton_picPath.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                image.setIcon(new ImageIcon(Pic_input.getText()));
                for(int i=0;i<N_screen;i++)
                    screens.get(i).setPicPath(Pic_input.getText());
            }
        });
        jPanel1.add(jLabel_setPic);
        jPanel1.add(Pic_input);
        jPanel1.add(jButton_see);
        jPanel1.add(jButton_picPath);

        jPanel.add(jPanel1);
        return jPanel;
    }

    private JMenuBar initMenu(){
        MenuItemListener menuItemListener = new MenuItemListener();
        JMenuBar jMenuBar = new JMenuBar();
        JMenu jMenu_file = new JMenu("文件");
        JMenuItem jMenuItem_open = new JMenuItem("打开");
        jMenuItem_open.setActionCommand("open");
        jMenuItem_open.addActionListener(menuItemListener);
        jMenu_file.add(jMenuItem_open);
        JMenuItem jMenuItem_save = new JMenuItem("保存");
        jMenuItem_save.setActionCommand("save");
        jMenuItem_save.addActionListener(menuItemListener);
        jMenu_file.add(jMenuItem_save);
        jMenu_file.addSeparator(); //分割线
        JMenuItem jMenuItem_exit = new JMenuItem("退出");
        jMenuItem_exit.setActionCommand("exit");
        jMenuItem_exit.addActionListener(menuItemListener);
        jMenu_file.add(jMenuItem_exit);

        JMenu jMenu_view = new JMenu("视图");
        JMenuItem jMenuItem_viewSettings = new JMenuItem("显示设置");
        jMenuItem_viewSettings.setActionCommand("viewSettings");
        jMenuItem_viewSettings.addActionListener(menuItemListener);
        jMenu_view.add(jMenuItem_viewSettings);

        JMenu jMenu_match = new JMenu("比赛");
        JMenuItem jMenuItem_score = new JMenuItem("分数纠正");
        jMenuItem_score.setActionCommand("changeScore");
        jMenuItem_score.addActionListener(menuItemListener);
        jMenu_match.add(jMenuItem_score);
        JMenuItem jMenuItem_showTotal = new JMenuItem("显示总分");
        jMenuItem_showTotal.setActionCommand("showTotal");
        jMenuItem_showTotal.addActionListener(menuItemListener);
        jMenu_match.add(jMenuItem_showTotal);


        JMenu jMenu_screen = new JMenu("计分屏");
        for(int i=1;i<=6;i++){
            JMenuItem jMenuItem = new JMenuItem("计分屏"+i);
            jMenuItem.setActionCommand("screen"+i);
            jMenuItem.addActionListener(menuItemListener);
            jMenu_screen.add(jMenuItem);
        }

        JMenu jMenu_networks = new JMenu("网络");

        jMenuBar.add(jMenu_file);
        jMenuBar.add(jMenu_view);
        jMenuBar.add(jMenu_match);
        jMenuBar.add(jMenu_screen);
        jMenuBar.add(jMenu_networks);
        return  jMenuBar;
    }

    public void setScore(int screen, int match, boolean team, int score){
        screens.get(screen-1).setScore(team,match,score);
        scoreTables.get(screen-1).updateScore(team,match,score);
    }

    class MenuItemListener implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            switch (e.getActionCommand()){
                case "open":
                    storageManager.reload();
                    break;
                case "save":
                    storageManager.save();
                    break;
                case "exit":
                    desktop.dispatchEvent(new WindowEvent(desktop,WindowEvent.WINDOW_CLOSING));
                    break;
                case "viewSettings": //显示设置
                    new ChangeStyle(screens,scoreTables);
                    break;
                case "screen1":
                    screens.get(0).showWindow();
                    break;
                case "screen2":
                    screens.get(1).showWindow();
                    break;
                case "screen3":
                    screens.get(2).showWindow();
                    break;
                case "screen4":
                    screens.get(3).showWindow();
                    break;
                case "screen5":
                    screens.get(4).showWindow();
                    break;
                case "screen6":
                    screens.get(5).showWindow();
                    break;
                case "changeScore":
                    new ChangeScore(screens, scoreTables, N_match);
                    break;
                case "showTotal":
                    new ShowTotal(screens,scoreTables);
                    break;
            }
        }
    }
}

